package com.coocaa.ops.common.core.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import com.coocaa.ops.common.tool.http.HttpCodeEnums;
import com.coocaa.ops.common.tool.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tangminghong
 * @date 2020-06-10 17:20
 */
@Slf4j
public abstract class BaseController {


    /**
     * 返回结果的json化-可去除null值字段
     *
     * @param data
     * @return
     */
    protected String render2Json(Object data) {
        return JsonUtil.obj2Json(data);
    }

    @ExceptionHandler({Exception.class})
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
        ModelMap modelMap = new ModelMap();
        handleException(e, modelMap, request);
        response.setContentType("application/json;charset=UTF-8");
        byte[] bytes = JSON.toJSONBytes(modelMap, new SerializerFeature[]{SerializerFeature.DisableCircularReferenceDetect});
        response.getOutputStream().write(bytes);
    }

    /**
     * 处理异常-Exception
     *
     * @param ex
     * @param modelMap
     */
    private void handleException(Throwable ex, ModelMap modelMap, HttpServletRequest request) {
        modelMap.put("code", HttpCodeEnums.INTERNAL_SERVER_ERROR.value().toString());
        String msg = ExceptionUtil.getStackTraceAsString(ex, 3);
        String url = request.getRequestURI();
        modelMap.put("url", url);
        modelMap.put("msg", msg);
    }
}
